/*
 * @Author: gk 
 *  文件资源
 * @Date: 2018-03-15 14:44:57 
 * @Last Modified by: gk
 * @Last Modified time: 2018-05-09 14:31:14
 */
layui.config({
}).use(['element', 'table', 'tree', 'treeGrid', 'zlSelectEx', 'zlPopSourceForm', 'zlPinYin', 'upload', 'dropdown', 'zlPrint'], function (exports) {
	var $ = layui.$
		, zlContext = layui.zlContext
		, layer = layui.layer
		, form = layui.form
		, upload = layui.upload
		, treeGrid = layui.treeGrid
		, zlPrint = layui.zlPrint
		, zlPinYin = layui.zlPinYin
		, zlConfig = layui.zlConfig
		, statusName = zlConfig.global.result.statusName
		, msgName = zlConfig.global.result.msgName
		, dataName = zlConfig.global.result.dataName
		, ERROR = zlConfig.global.result.errorState
		, OK = zlConfig.global.result.okState
		, fullheight = 'full-80'
		, CATLOG = 'reports'
		, REPORT_EXT = 'rpx|sht'
		, REPORT_MIME = 'report/rpt,report/sht';
	$(window).on('resize', function () {
		$('.docking-left').height($(window).height() - 10);
		$('.docking-fill').height($(window).height() - 10);
	}).resize();

	var fromlayerIndex;
	var pingps = {
		'5758F06288714A51BDC1F1E17E3FEC4C': '润乾'
		, '385D6FF9B8344D2D86F17BF98218B74A': '帆软'
		, 'AFA32A3F2BE84226B81A2DAE6EB702F7': '快搭'
	};
	var reptypes = {
		'75AF609D5C6A43CEBA584532470D3033': '普通报表'
		, 'D910CAB4442F4E9AB0B3D63D7980CF6A': '填报报表'
	};
	var iconsetting = "{type:'image'," +
    'coltitle:[[' +
    '{ type: "numbers", fixed: "left", title: "#" },' +
    '{ type: "checkbox", fixed: "left" },' +
    '{ field: "WJZY_MINGC", title: "名称", width: 100 },' +
    '{ field: "WJZY_BIANH", title: "编号", width: 150 },' +
    '{ field: "WJZY_ZIYLJ", title:"资源", width: 150,templet: "<div><img atl=' + "''" + "src='" + layui.cache['contentPath'] + "{{ d.WJZY_ZIYLJ}}" + "'" + '></div>"}]],' +
    "limit:10,formtitle:'选择图标',page:true, id:'WJZY_ZIYLJ',name : 'WJZY_ZIYLJ', method:'post',params:'{WJZY_LEIX:0}' ,dataurl:'" + layui.cache['contentPath'] + "/manager/corefilesres/query'}";
  
	//渲染报表列表
	treeGrid.render({
		elem: '#tbReport'
		, height: fullheight
		, response: zlConfig.global.gridResponse
		, limit: 10000
		, treeId: 'RWID'//树形id字段名称
		, treeUpId: 'SYS_PARENTID'//树形父id字段名称
		, treeShowName: 'REP_MINGC'//以树形式显示的字
		, cols: [[ //表头
			{ type: 'checkbox', fixed: 'left' }
			, { field: 'REP_MINGC', width: '175', title: '名称' }
			, { field: 'REP_BIANH', width: '100', title: '编号' }
			, {
				field: 'REP_PINP', width: '90', title: '品牌', templet: function (d) {
					return '<span>' + pingps[d.REP_PINP] + '</span>'
				}
			}
			, {
				field: 'REP_LEIX', width: '80', title: '类型', templet: function (d) {
					return '<span>' + reptypes[d.REP_LEIX] + '</span>'
				}
			}
			, {
				field: 'REP_TUB', width: '60', title: '图标', templet: function (d) {
					return d.REP_TUB ? '<img atl="" src="' + layui.cache['contentPath'] + d.REP_TUB + '">' : '';
				}
			}
			, { field: 'REP_LUJ', width: '275', title: '报表链接' }
			, { field: 'REP_WENJLJ', width: '275', title: '文件路径' }
			, { fixed: 'right', field: 'OPTION', width: 250, title: '操作', align: 'center', toolbar: '#barReport' }
		]]
		, event:
		{
			onRowdbClick: function (field, row) {
				gridAction.viewRow(row);
			}
		}
		, page: false
	});
	var treeTable = {
		getSelectedNodes: function () {
			var checkStatus = treeGrid.checkStatus('tbReport');
			return checkStatus.data;
		}
	}

	var gridAction = {
		currentEditObj: undefined,
		gridEdit: function (parentrow, row, type, readonly) {
			var readonly = readonly && readonly != 0 ? 'disabled' : '';
			var frm = [
				'<div class="site-block" lay-filter="divgridField"> <form id ="frmEditGrid" class="layui-form"  action="">'
				, '	<div class="layui-form-item layui-hide">'
				, '		<div class="layui-input-block">'
				, '			<input type="text" name="EDITTYPE" class="layui-input">'
				, '			<input type="text" name="SYS_PARENTID" class="layui-input">'
				, '			<input type="text" name="RWID" class="layui-input">'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">名称</label>'
				, '		<div class="layui-input-block">'
				, '			<input type="text" name="REP_MINGC" ' + readonly + ' lay-verify="required" placeholder="请输入名称" class="layui-input">'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">编号</label>'
				, '		<div class="layui-input-block">'
				, '			<input type="text" name="REP_BIANH" ' + readonly + ' lay-verify="required" placeholder="请输入编号" class="layui-input">'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">品牌</label>'
				, '		<div class="layui-input-block">'
				, '	  		<select name="REP_PINP" lay-verify="required" ' + readonly + ' placeholder="请选择品牌"  zlcomponent class="select-ext" settings="{titlefield: \'VALUE\', valuefield: \'DCMX_KEY\',dataurl:\'' + layui.cache['contentPath'] + '/manager/coredictionary/querydictionarybyid?RWID=EBB0373768D8465E8B946F5099028CA9\'}">'
				, '	  		</select>'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">类型</label>'
				, '		<div class="layui-input-block">'
				, '	  		<select name="REP_LEIX" lay-verify="required" ' + readonly + ' placeholder="请选择类型"  zlcomponent class="select-ext" settings="{titlefield: \'VALUE\', valuefield: \'DCMX_KEY\',dataurl:\'' + layui.cache['contentPath'] + '/manager/coredictionary/querydictionarybyid?RWID=E86C8DB4D90245EE85748FF84756877D\'}">'
				, '	  		</select>'
				, '		</div>'
				, '	</div>'
				, ' <div class="layui-form-item">'
				, '       <div class="layui-col-md12">'
				, '           <label class="layui-form-label">图标</label>'
				, '           <div class="layui-input-block" id="smalldiv">'
				, '               <div name="REP_TUB" zlcomponent class="layui-form-select zlPopSourceForm">'
				, '               </div>'
				, '           </div>'
				, '       </div>'
				, '   </div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">报表链接</label>'
				, '		<div class="layui-input-block">'
				, '				<textarea placeholder="报表链接" ' + readonly + ' name="REP_LUJ" class="layui-textarea"></textarea>'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<div class="layui-input-block">'
				, '		  <button class="layui-btn" lay-submit lay-filter="frmEditGrid"  ' + readonly + '>保存</button>'
				, '		  <button type="reset" class="layui-btn layui-btn-primary ' + (type == 'edit' ? 'layui-hide"' : '"') + readonly + '>重置</button>'
				, '		</div>'
				, '	</div>'
				, '</form></div>'
			];
			layer.open({
				type: 1,
				title: readonly == 'disabled' ? '查看' : (type == 'edit' ? '编辑' : '新增'),
				id: 'qingchumxLayer',
				area: ['100%', '100%'],
				content: frm.join(''),
				success: function (layero, index) {
					$('div[name="REP_TUB"]').attr('settings', iconsetting);
					if (type == 'edit') {
						zlContext.autoFill($('#frmEditGrid'), row);
						$('#frmEditGrid input[name=EDITTYPE]').val('edit');
						form.render();
					}
					else {
						/**设置隐藏属性*/
						$('#frmEditGrid input[name=EDITTYPE]').val('new');
						if (parentrow) {
							$('#frmEditGrid input[name=SYS_PARENTID]').val(parentrow['RWID']);
						}
						//由于layui是主动刷新需要重新刷新才能显示出状态
						form.render();
						$('#frmEditGrid input[name=REP_MINGC]').change(function () {
							var v = $('#frmEditGrid input[name=REP_MINGC]').val();
							/**设置报表名 */
							var v1 = zlPinYin.C(v);
							$('#frmEditGrid input[name=REP_BIANH]').val(v1);
							form.render();
						});
					}
					fromlayerIndex = index;
				}
			});
		},
		viewRow: function (row) {
			gridAction.gridEdit(null, row, 'edit', true);
		},
		newRow: function () {
			var nodes = treeTable.getSelectedNodes();
			gridAction.gridEdit(nodes.length > 0 ? nodes[0] : null, null, 'new');
		},
		editRow: function (row) {
			gridAction.gridEdit(null, row, 'edit');
		},
		deleteRows: function (rows) {
			if (rows.length == 0) {
				zlContext.warnMsg('请选择需要删除的报表');
				return;
			}
			for (var i = 0; i < rows.length; i++) {
				if (rows[i].children.length > 0) {
					zlContext.warnMsg(rows[i].REP_MINGC + "功能节点下还有子功能，请先删除子功能");
					canpost = false;
					return;
				}
			}
			zlContext.confirm('询问', '是否要删除选择的报表?', function (index) {
				// var param = { id: rows[0]['RWID'] };
				//提交删除
				zlContext.deletePost(layui.cache['contentPath'] + '/manager/corereport/remove', { id: rows[0]['RWID'] }, function (result) {
					if (result[statusName] == OK) {
						gridAction.currentEditObj.del();
					}
					else {
						zlContext.errorMsg(result[msgName]);
					}
				});
				layer.close(index);
			});
		},
		export: function (row) {
			if ($("#ifexport").length == 0) {
				$("body").append('<iframe id=ifexport style="display:none"></iframe>');
			}
			$("#ifexport").attr("src", layui.cache['contentPath'] + row['REP_WENJLJ']);
			iframe = $("#ifexport")[0];
			iframe.onload = iframe.onreadystatechange = function iframeload() {
				if (!iframe.readyState || iframe.readyState == "complete") {
					//alert("Local iframe is now loaded.");
				}
			};
		},
		sumbit: function (fields) {
			var editType = $('#frmEditGrid input[name=EDITTYPE]').val();
			// var param = JSON.stringify(fields);
			if (editType == 'new') {
				zlContext.put(layui.cache['contentPath'] + '/manager/corereport/add', fields, function (result) {
					if (result[statusName] == OK) {
						gridAction.refreshGrid(editType, result[dataName]);
						layer.close(fromlayerIndex);
						return true;
					}
					else {
						zlContext.errorMsg(result[msgName]);
					}
				});
			} if (editType == 'edit') {
				zlContext.post(layui.cache['contentPath'] + '/manager/corereport/modify', fields, function (result) {
					if (result[statusName] == OK) {
						gridAction.refreshGrid(editType, fields);
						layer.close(fromlayerIndex);
						return true;
					}
					else {
						zlContext.errorMsg(result[msgName]);
					}
				});
			}
			return false;
		},
		search: function () {
			var param = {};
			param['REP_MINGC'] = $('#edtSeacherValue').val();
			layui.event('WM_USERDEF',
				zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, param);
		},
		refresh: function (node) {
			$('#edtSeacherValue').val("")
			var param = {};
			param['REP_MINGC'] = $('#edtSeacherValue').val();
			layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, param);
		},
		refreshGrid: function (type, row) {
			/**刷新行 */
			if (type == 'edit' && gridAction.currentEditObj) {
				gridAction.currentEditObj.update(row);
			}
			else if (type == 'new') {
				treeGrid.reload('tbReport');
			}
		},
		getParams: function () {
			var param = {};
			param['REP_MINGC'] = $('#edtSeacherValue').val();
			var chkRows = treeTable.getSelectedNodes();
			var chkrwids = [];
			$.each(chkRows, function (index, row) {
				chkrwids.push(row.RWID);
			});
			param['chkrwids'] = chkrwids.join(',');
			return param;
		}
	}
	$('#btnReportRefresh').on('click', function () {
		gridAction.refresh(null);
	});
	$('#btnReportNew').on('click', function () {
		gridAction.newRow();
	});
	$('#btnReportDelete').on('click', function () {
		var rows = treeTable.getSelectedNodes();
		gridAction.deleteRows(rows);
	});
	$('#btnSeacher').on('click', function () {
		gridAction.search();
	});
	$('#edtSeacherValue').on('keypress', function (event) {
		if (event.keyCode == 13) {
			gridAction.search();
		}
	});
	treeGrid.on('tool(tbReport)', function (obj) {
		var row = obj.data; //获得当前行数据
		var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
		var tr = obj.tr; //获得当前行 tr 的DOM对象
		if (layEvent === 'detail') { //查看
			gridAction.viewRow(row)
		} else if (layEvent === 'del') { //删除
			gridAction.currentEditObj = obj;
			gridAction.deleteRows([row]);
		} else if (layEvent === 'edit') { //编辑
			gridAction.currentEditObj = obj;
			gridAction.editRow(row);
		} else if (layEvent == 'export') {
			gridAction.export(row);
		} else if (layEvent == 'import') {
			gridAction.currentEditObj = obj;
		}
	});
	//提交
	form.on('submit(frmEditGrid)', function (frm) {
		return gridAction.sumbit(frm.field);
	});
	//监听刷新的事件
	layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, null, function (param) {
		var index = layer.msg('数据查询中，请稍候...', { icon: 16, time: false, shade: 0.1 });
		var loadGridData = function (tableId, url, param) {
			treeGrid.reload(tableId, {
				url: url
				, height: fullheight
				, page: false
				, limit: 10000
				, method: 'post'
				, where: param
				, done: function (res, curr, count) {
					layer.close(index);
					upload.render({
						elem: '.reportImport'
						, url: layui.cache['contentPath'] + '/manager/corereport/upload/'
						, data: {
							catlog: CATLOG, id: function () {
								return gridAction.currentEditObj.data['RWID'];
							}
						}
						, accept: 'file'
						, acceptMime: REPORT_MIME
						, exts: REPORT_EXT
						, before: function () {
							winIndex = layer.msg('导入中，请稍候...', { icon: 16, time: false, shade: 0.1 });
						}
						, done: function (res, index, upload) {
							layer.close(winIndex);
							if (res[statusName] != OK) {
								return layer.msg('导入失败' + res[msgName]);
							}
							else {
								gridAction.currentEditObj.update(res[dataName]);
							}
							zlContext.successMsg('导入完毕');
						}
					})
				}
			});
		}
		//刷新
		loadGridData('tbReport', layui.cache['contentPath'] + '/manager/corereport/query', param);
	});

	//注册打印获取参数回调函数
	zlPrint.regeditparamCallBack("aaaaaa", gridAction.getParams);
	zlPrint.regeditparamCallBack("bbbb", gridAction.getParams);

	gridAction.refresh(null);
});